package com.agriculture.controller;

import com.agriculture.entity.GeoParcel;
import com.agriculture.repository.GeoParcelRepository;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityNotFoundException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/parcels")
@CrossOrigin(origins = "*")
public class GeoParcelController {
    
    @Autowired
    private GeoParcelRepository parcelRepository;
    
    private final GeometryFactory geometryFactory = new GeometryFactory();
    
    @GetMapping
    public List<GeoParcel> getAllParcels() {
        return parcelRepository.findAll();
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<GeoParcel> getParcelById(@PathVariable Integer id) {
        Optional<GeoParcel> parcel = parcelRepository.findById(id);
        if (parcel.isPresent()) {
            return ResponseEntity.ok(parcel.get());
        } else {
            throw new EntityNotFoundException("地块不存在");
        }
    }
    
    @PostMapping
    public ResponseEntity<GeoParcel> createParcel(@RequestBody Map<String, Object> parcelData) {
        GeoParcel parcel = new GeoParcel();
        parcel.setParcelName((String) parcelData.get("parcelName"));
        parcel.setArea((Double) parcelData.get("area"));
        parcel.setSoilType((String) parcelData.get("soilType"));
        
        // 处理边界数据
        Map<String, Object> boundary = (Map<String, Object>) parcelData.get("parcelBoundary");
        if (boundary != null && boundary.containsKey("coordinates")) {
            List<List<Map<String, Double>>> coordinates = 
                (List<List<Map<String, Double>>>) boundary.get("coordinates");
            
            if (!coordinates.isEmpty()) {
                List<Map<String, Double>> ring = coordinates.get(0);
                Coordinate[] coords = new Coordinate[ring.size()];
                
                for (int i = 0; i < ring.size(); i++) {
                    Map<String, Double> point = ring.get(i);
                    coords[i] = new Coordinate(point.get("x"), point.get("y"));
                }
                
                LinearRing linearRing = geometryFactory.createLinearRing(coords);
                Polygon polygon = geometryFactory.createPolygon(linearRing);
                parcel.setParcelBoundary(polygon);
            }
        }
        
        GeoParcel savedParcel = parcelRepository.save(parcel);
        return ResponseEntity.status(HttpStatus.CREATED).body(savedParcel);
    }
    
    @GetMapping("/{id}/area")
    public ResponseEntity<Map<String, Object>> getParcelArea(@PathVariable Integer id) {
        Double area = parcelRepository.calculateParcelArea(id);
        if (area != null) {
            Map<String, Object> response = new HashMap<>();
            response.put("parcelId", id);
            response.put("area", area);
            response.put("unit", "平方米");
            response.put("calculatedTime", LocalDateTime.now());
            return ResponseEntity.ok(response);
        } else {
            throw new EntityNotFoundException("地块不存在");
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteParcel(@PathVariable Integer id) {
        parcelRepository.deleteById(id);
        return ResponseEntity.ok().build();
    }
}